<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片预加载</title>
    <script src="../application/vue.js"></script>
    <style>
        .img {
            width: 300px;
            height: 300px;
            border: 1px solid #ccc;
            border-radius: 10px;
        }

        .imgbox {
            width: 300px;
            height: 300px;
            border: 1px solid #ccc;
            border-radius: 10px;
            display:inline-block;
        }
    </style>
</head>

<body>
    <div class="app">
        <img class="img" v-preload:cover="imgsrc1">
        <img class="img" v-preload:fill="imgsrc2">
        <img class="img" v-preload:scale-down="imgsrc2">
        <hr>
        <div class="imgbox" v-preload:contain.bg="imgsrc1"></div>
        <div class="imgbox" v-preload:cover.bg="imgsrc1"></div>
    </div>
</body>
<script>
    Vue.directive("preload", function (el, binding) {
        //在真正图片被显示出来之前，先用gif加载图片模拟页面被加载
        if (binding.modifiers.bg) {//用来调整背景图片的大小
            el.style.backgroundImage = `url(${"../image/5-121204193935-51.gif"})`;
            el.style.backgroundRepeat = "no-repeat";
            el.style.backgroundPosition = "center center";
        } else {//object-fit、object-position用来修饰img照片的大小的样式
            el.src = "../image/5-121204193935-51.gif";
            el.style.objectFit = "none";
            el.style.objectPostion = "center";
        }
        let img = new Image();//创建一个img标签元素
        console.log(binding);//可以看到binding中有哪些属性分别代表着什么意思
        img.src = binding.value;//让创建的img元素的地址指向所绑定指令的值
        img.onload = function () {//待页面照片加载完成后再显示最后的图片
            if (binding.modifiers.bg) {
                el.style.backgroundImage = `url(${binding.value})`;
                el.style.backgroundSize=binding.arg;
            } else {
                el.src = binding.value;
                el.style.objectFit=binding.arg;
                //DOM.style.className="样式";
            }
        }
    })
    new Vue({
        el: ".app",
        data: {
            imgsrc1: "../image/u=1878125254,116198046&fm=11&gp=0.jpg",
            imgsrc2: "../image/u=3615222344,3211418289&fm=26&gp=0.jpg"
        }
    })
</script>

</html>